package com.piggy.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piggy.common.core.enums.RedisKeyEnums;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.exception.CustomException;
import com.piggy.common.datascope.annotation.DataScope;
import com.piggy.common.redis.cache.CacheUtils;
import com.piggy.system.api.domain.SysDept;
import com.piggy.system.api.domain.SysRole;
import com.piggy.system.api.domain.SysUser;
import com.piggy.system.domain.vo.TreeSelect;
import com.piggy.system.enums.BusineseTypeEnum;
import com.piggy.system.enums.OrgDeptIdEnum;
import com.piggy.system.enums.OrgTypeEnum;
import com.piggy.system.mapper.SysDeptMapper;
import com.piggy.system.mapper.SysRoleMapper;
import com.piggy.system.mapper.SysUserMapper;
import com.piggy.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author shark
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        List<SysDept> deptList = baseMapper.selectDeptList(dept);
        cacheListIfAbsent(deptList);
        return deptList;
    }

    /**
     * 获取部门列表(如供应商、经销商、资方列表)根据企业类型
     *
     * @param busineseType 企业类型 (0核心企业1供应商2经销商3金融机构)
     * @return 部门列表
     */
    @Override
    public List<SysDept> getDeptListByOrgType(String sceneKey,Integer busineseType) {
        if(sceneKey!=null&&busineseType!=null){
            List<Long> deptIds= baseMapper.getDeptIds(sceneKey,busineseType);
            if(CollectionUtil.isNotEmpty(deptIds)){
                List<SysDept> deptList=this.list(new LambdaQueryWrapper<SysDept>().in(SysDept::getDeptId,deptIds));
                return deptList;
            }else{
                return new ArrayList<SysDept>();
            }

        }else{
            return new ArrayList<SysDept>();
        }
    }


    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectById(roleId);
        return baseMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return getCache(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        Long count =  count(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getStatus, 0)
                .apply("find_in_set({0}, ancestors)", deptId));
        return count.intValue();
    }


	/**
	 * 根据用户所在部门，获取该用户所属组织类型
	 **/
	@Override
	public Integer getOrgType(Long deptId,String sceneKey) {
        SysDept dept = this.getCache(deptId);
        if (dept != null && (dept.getDeptId().equals(OrgDeptIdEnum.PLATFORM.getCode().longValue()) || dept.getAncestors().contains(String.valueOf(OrgDeptIdEnum.PLATFORM.getCode())))) {
            //101  平台
            return OrgTypeEnum.PLATFORM.getCode();//返回3
        }

        //返回sceneId
        //Long sceneId= baseMapper.getSceneIdBySceneKey(sceneKey);
        Long orgDeptId=this.getOrgDeptId(deptId);
        Long busineseId= baseMapper.getBusinessIdByDeptId(orgDeptId);

        if(orgDeptId==null||busineseId==null){
            return null;
        }

        //获取tdms中的企业类型
        Integer busineseType=baseMapper.getBusineseType(sceneKey,busineseId);
        Console.log("********busineseType:"+busineseType);

        if("incar".equals(sceneKey)){
            //进口车

            if(busineseType!=null&& BusineseTypeEnum.CORE.getCode().equals(busineseType)){
                //0核心
                return OrgTypeEnum.ZHONGWAIYUN.getCode();//返回2 中外运
            }else if (busineseType!=null&& BusineseTypeEnum.JXS.getCode().equals(busineseType)) {
                //2经销商
                return OrgTypeEnum.CHESHANG.getCode();//返回1 车商
            }else if (busineseType!=null&& BusineseTypeEnum.BANK.getCode().equals(busineseType)) {
                //3金融机构
                return OrgTypeEnum.BANK.getCode();//返回4 金融机构
            }else if (busineseType!=null&& BusineseTypeEnum.OTHER.getCode().equals(busineseType)) {
                //4其它
                return  OrgTypeEnum.OFFSHORE.getCode();//返回5 离岸公司
            }else{
                return OrgTypeEnum.UNKNOWN.getCode();//返回0
            }

        }else{
            return  busineseType;
        }

	}

	/**
	 * 获取用户所属组织的部门ID(如车商部门ID、资方部门ID、中外运部门ID、平台部门ID)
	 */
	@Override
	public Long getOrgDeptId(Long deptId) {

        SysDept dept = this.getCache(deptId);
        String[] deptArr = dept.getAncestors().split(",");
        Long orgDeptId = null;//车商部门id  如：124 招商汽贸、125一汽汽贸 ；资方部门id  如：118 中商国能、119 建设银行； 中外运部门id  如：112 中外运

        if(OrgDeptIdEnum.SYSADMIN.getCode().equals(deptId.intValue())){
            //100 系统管理员
            orgDeptId = deptId;
        } else {
            if (deptArr.length == 2) {
                //直接在第2层，取其部门id
                orgDeptId = dept.getDeptId();
            } else if (deptArr.length == 3 || deptArr.length == 4 || deptArr.length == 5 || deptArr.length == 6 || deptArr.length == 7 || deptArr.length == 8 || deptArr.length == 9) {
                //其部门在第3层、第4层、第5层、第6层、第7层、第8层、第9层，取其Ancestors数组下标为2
                orgDeptId = Long.valueOf(deptArr[2]);
            } else {
            }
        }
        return orgDeptId;
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        Long result = count(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getParentId, deptId)
                .last("limit 1"));
        return result > 0L ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        Long result = userMapper.selectCount(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getDeptId, deptId));
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = Validator.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = getOne(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptName, dept.getDeptName())
                .eq(SysDept::getParentId, dept.getParentId())
                .last("limit 1"));
        if (Validator.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = getCache(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        int insert = baseMapper.insert(dept);
        cache(dept);
        return insert;
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = getCache(dept.getParentId());
        SysDept oldDept = getCache(dept.getDeptId());
        if (Validator.isNotNull(newParentDept) && Validator.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = baseMapper.updateById(dept);
        removeCache(dept.getDeptId());
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = getById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        update(null,new LambdaUpdateWrapper<SysDept>()
                .set(StrUtil.isNotBlank(dept.getStatus()),
                        SysDept::getStatus,dept.getStatus())
                .set(StrUtil.isNotBlank(dept.getUpdateBy()),
                        SysDept::getUpdateBy,dept.getUpdateBy())
                .in(SysDept::getDeptId, Arrays.asList(dept.getAncestors().split(","))));
        cacheList1(Arrays.asList(dept.getAncestors().split(",")));
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = list(new LambdaQueryWrapper<SysDept>()
                .apply("find_in_set({0},ancestors)",deptId));
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseMapper.updateDeptChildren(children);
        }
        cacheList(children);
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        removeCache(deptId);
        return baseMapper.deleteById(deptId);
    }

    @Override
    public List<SysDept> queryDeptAll() {
        List<SysDept> list = this.selectDeptList(new SysDept());
        cacheListIfAbsent(list);
        return list;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (Validator.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * cache redis
     */
    private void cache(SysDept sysDept) {
        CacheUtils.cache(sysDept, RedisKeyEnums.SysDept.getKey(sysDept.getDeptId()), RedisKeyEnums.SysDept.getDay(), TimeUnit.DAYS);
    }

    /**
     * cache redis
     */
    private void cacheIfAbsent(SysDept sysDept) {
        CacheUtils.cacheIfAbsent(sysDept, RedisKeyEnums.SysDept.getKey(sysDept.getDeptId()), RedisKeyEnums.SysDept.getDay(), TimeUnit.DAYS);
    }

    /**
     * cache redis
     */
    private void cacheListIfAbsent(List<SysDept> sysDeptList) {
        if (CollectionUtil.isNotEmpty(sysDeptList)) {
            sysDeptList.forEach(this::cacheIfAbsent);
        }
    }

    /**
     * cache redis
     */
    private void cacheList(List<SysDept> sysDeptList) {
        if (CollectionUtil.isNotEmpty(sysDeptList)) {
            sysDeptList.forEach(this::cache);
        }
    }

    private void cacheList1(List<String> idList) {
        if (CollectionUtil.isNotEmpty(idList)) {
            List<SysDept> sysDeptList = baseMapper.selectList(new LambdaQueryWrapper<SysDept>().in(SysDept::getDeptId, idList));
            cacheList(sysDeptList);
        }
    }

    private SysDept getCache(Long deptId) {
        return CacheUtils.getCache(deptId, RedisKeyEnums.SysDept, SysDept.class, new CacheUtils.ICache<SysDept>() {
            @Override
            public SysDept invoke() {
                SysDept dept = baseMapper.selectById(deptId);
                cache(dept);
                return dept;
            }
        });
    }

    private void removeCache(Long deptId) {
        String key = RedisKeyEnums.SysDept.getKey(deptId);
        CacheUtils.remove(key);
    }

}
